//
//  MYOAuthViewController.swift
//  MYSinaWeico
//
//  Created by Magic Yu on 16/4/9.
//  Copyright © 2016年 Magic Yu. All rights reserved.
//

//private let userInfoKey = "com.mySinaWeico.userInfoKey"

import UIKit
import SVProgressHUD

class MYOAuthViewController: UIViewController {

    //自定义根视图为webView
    let webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "fullAccount")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "back")

        //使用webView加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    func back() {
    dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    func fullAccount() {
        
        //code=186629e3f9121bef385456ad08348f78
    
        //设置默认的账号和密码
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '2418989905@qq.com',document.getElementById('passwd').value='77qiqi1212;'")
    }
    

}
//遵守webView代理协议
extension MYOAuthViewController:UIWebViewDelegate {

    func webViewDidStartLoad(webView: UIWebView) {
        //开启等待指示器
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        //
        title = webView.stringByEvaluatingJavaScriptFromString("document.title")
        //取消用户等待指示器
        SVProgressHUD.dismiss()
    }
    //协议方法返回值为bool类型 如果返回true 可以正常工作 如果返回false 不能正常工作
    //在授权成功的回调页中 授权code
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString ?? ""
        print(urlString)
        let flag = "code="
        if urlString.containsString(flag) {
            //授权成功
            let range = urlString.rangeOfString(flag)!
            let code = urlString.substringFromIndex(range.endIndex)
            print(code)
            //使用授权码 获取ccessToken
//            loadAccessToken(code)
            MYUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                if !isSuccess {
                SVProgressHUD.showErrorWithStatus("登录失败")
                    return
                }
                
                SVProgressHUD.showErrorWithStatus("登陆成功")
            })
            
            //不加载授权成功的回调页面
            return false
        }
        return true
    }
    
    //MARK: 移到MYUserAccountViewModel类中
    
//    //使用授权码 请求accesstoken
//    private func loadAccessToken(code: String) {
//    let urlString = "https://api.weibo.com/oauth2/access_token"
////        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
//        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
//        HMNetworkTools.sharedTools.request(.POST, urlString: urlString, parameters: parameters) { (result, error) -> () in
//            if error != nil {
//                print(error)
//            SVProgressHUD.showErrorWithStatus("世界上最遥远的距离就是没网")
//                return
//            }
//            
//            //程序走到这 就一定没有错误
//            print("授权成功")
//            
//            //获取用户信息 在请求成功的回调中
//            self.loadUserInfo(result!)
//            
//        }
//        
//    }
//    
//    private func loadUserInfo(tokenResult: AnyObject) {
//    
//        //尝试将result转换为字典
//        guard let dict = tokenResult as? [String: AnyObject] else {
//        
//            SVProgressHUD.showErrorWithStatus("数据错误")
//            return
//        }
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        let token = dict["access_token"]!
//        let uid = dict["uid"]!
//        //字典数组中不能添加nil 因为可选项可能是nil 所以字典不能添加可选项 所以要转token和uid换为必选项
//        let parameters = ["access_token":token, "uid":uid]
//        
//        HMNetworkTools.sharedTools.request(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in
//            if error != nil {
//            SVProgressHUD.showErrorWithStatus("世界上最遥远的距离就是没网")
//                print(error)
//                return
//            }
//            
//            print("获取用户信息成功")
//            
//            //将用户信息保存起来
//            print(result)
//            //将anyObject转换成字典类型
//            guard var userInfoDict = result as? [String: AnyObject] else {
//            
//                SVProgressHUD.showErrorWithStatus("数据结构错误")
//                return
//            }
//            
//            //合并字典
//            for(k,v) in dict {
//            userInfoDict[k] = v
//            }
//            print(userInfoDict)
//            
//            //保存完整的字典信息  偏好设置中不能保存nil
//            let userDefaults = NSUserDefaults.standardUserDefaults()
//            
//            //1.将字典信息转换为模型对象
//            let account = MYUserAccount(dict: userInfoDict)
//            //2.获取模型对象字典信息
//            let keys = ["access_token","avatar_large","name","expires_in","uid"]
//            let accountDict = account.dictionaryWithValuesForKeys(keys)
//            //3.将对象的字典信息保存在偏好设置中
//            userDefaults.setObject(accountDict, forKey: userInfoKey)
//            //4.同步
//            userDefaults.synchronize()
//            
//            print(NSHomeDirectory())
//            
//        }
//    }
}











